<?php

namespace App\Http\Controllers\manage;

use App\groupModel;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Validator;

class groupController extends Controller
{
    public function index(Request $request)
    {
        //当前页面标题
        $title = '分组管理';
        $groupModel = new groupModel();
        //分组总数
        $count = $groupModel->count();
        //分组信息
        $groups = $groupModel->get();

        if ($request->method() == 'POST') {
            $messages = [
                'name.required' => '您没有填写 分组名'
            ];

            $rules = [
                'name' => 'required'
            ];

            $validator = Validator::make($request->input(), $rules, $messages);
            $validator->validate();

            if (empty($GID = $request->input('GID'))) {
                //新建分组
                $groupModel->name = $request->input('name');
                $groupModel->text = $request->input('text');
                $groupModel->level = 1;
                $groupModel->creator = session('user');
                $groupModel->save();
                $validator->errors()->add('name', '已经新建分组！');
                return back()->withErrors($validator);
            } else {
                //编辑分组
                $group = $groupModel->where('GID', $GID)->first();
                $group->name = $request->input('name');
                $group->text = $request->input('text');
                $group->save();
                $validator->errors()->add('name', '成功保存修改！');
                return back()->withErrors($validator);
            }
        }
        return view("manage/group", compact('title', 'count', 'groups'));
    }

    //删除分组
    public function groupDel(Request $request)
    {
        $messages = [
            'GID.required' => '参数异常'
        ];

        $rules = [
            'GID' => 'required'
        ];

        $validator = Validator::make($request->input(), $rules, $messages);
        $validator->validate();

        $GID = $request->input('GID');
        $count = groupModel::where('GID', $GID)->delete();
        if ($count == 1) {
            $validator->errors()->add('name', '已删除分组');
            return back()->withErrors($validator);
        } else {
            $validator->errors()->add('name', '删除分组失败');
            return back()->withErrors($validator);
        }
    }
}
